package com.wanaofu.managedbeans;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;

import com.wanaofu.model.ProductInfo;
import com.wanaofu.service.ProductService;
import com.wanaofu.utils.FacesUtils;

@ManagedBean(name = "productMaintainBean")
@RequestScoped
public class ProductMaintainBean implements java.io.Serializable {
	private static final long serialVersionUID = -5370185335689528321L;
	
	private ProductInfo operatedProduct;
    private String opCode;
    
	@ManagedProperty(name = "productService", value = "#{productService}")
	private ProductService productService;
    
	public ProductMaintainBean() {
		System.out.println("===========in ProductMaintainBean Constructor===" );
	}

	@PostConstruct
	public void initProductBean() {
        System.out.println("===========in initProductBean===============opCode:"  + this.opCode );
        
		this.opCode = FacesUtils.getRequestParameter("opCode") ;
		
		System.out.println("===========in initProductBean===============opCode:"  + this.opCode );
		
		if (opCode != null && opCode.length() > 0) {
			operatedProduct = productService.getProductInfoById(this.opCode) ;
		} 
	}
	
	public String closeMaintainedProduct() {
		System.out.println("=============toControlProduct==============opCode:" + opCode);
		System.out.println("===========ready to return ===this.code:" + this.opCode);
 
		return "product_control?faces-redirect=true&amp;opCode=" + this.opCode ;
	}	
	
	private String handleImagePath(String path) {
		if (path.lastIndexOf("/")>0) {
			System.out.println("======:" + path.substring(path.lastIndexOf("/")+1) );
			return path.substring(path.lastIndexOf("/")+1) ;
		}
		return path ;
	}
	
	public String saveMaintainedProduct() {
		System.out.println("=============saveMaintainedProduct==============opCode:" + this.opCode );
		
		if (opCode != null && opCode.length() > 0) {
			System.out.println("======picture:" + this.operatedProduct.getPicture());
			System.out.println("======shotname:" + this.operatedProduct.getShortName());
			this.operatedProduct.setPicture(handleImagePath(operatedProduct.getPicture())) ;
			this.productService.maintainProductInfo(this.operatedProduct) ;
			FacesUtils.saveRedirectMessage("save OK!") ;
		} 
		
		//&amp; 
		return "product_control?faces-redirect=true&amp;opCode=" + opCode ;
	}

	
	
	public ProductInfo getOperatedProduct() {
		return operatedProduct;
	}

	public void setOperatedProduct(ProductInfo operatedProduct) {
		this.operatedProduct = operatedProduct;
	}

	public String getOpCode() {
		return opCode;
	}

	public void setOpCode(String opCode) {
		this.opCode = opCode;
	}

	public ProductService getProductService() {
		return productService;
	}

	public void setProductService(ProductService productService) {
		this.productService = productService;
	}	
	
	
}
